package com.huishen.edrivenew.widget;

import java.util.*;

import com.huishen.edrivenew.AppContext;
import com.huishen.edrivenew.R;
import com.huishen.edrivenew.bean.DateBean;

import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;

/**
 * 日历显示详情页
 * @author wu
 *
 */

public class CalendarPagerFragment extends Fragment {

    public static final String INDEX = "index", DATE_BEGIN = "begin", DATE_END = "end",
            COLORS = "colors";
    
    private int mMonthIndex;
    
    private Date beginDate, endDate; // 日历控件的可选区间
    private int[] colors; // 可选区域的颜色值
    private boolean isSection = false;

//    private CalendarGridViewAdapter adapter;
    private CalendarGridAdapter adapter;
    
    
    public static CalendarPagerFragment create() {
        return new CalendarPagerFragment();
    }
    

    public static CalendarPagerFragment create(int monthIndex) {
        CalendarPagerFragment fragment = new CalendarPagerFragment();
        Bundle args = new Bundle();
        args.putInt(INDEX, monthIndex);
        fragment.setArguments(args);
        return fragment;
    }
    
    public static CalendarPagerFragment create(int monthIndex, String beginDate, String endDate,
            int[] colors) {
        CalendarPagerFragment fragment = new CalendarPagerFragment();
        Bundle args = new Bundle();
        args.putInt(INDEX, monthIndex);
        args.putString(DATE_BEGIN, beginDate);
        args.putString(DATE_END, endDate);
        args.putIntArray(COLORS, colors);
        fragment.setArguments(args);
        return fragment;
    }

    
    /**
     * 设置时间数据
     */
    public void getDateBeans() {
        AppContext.getInstance().days = DateBean.getDays();
    }
    

    /**
     * 设置可选区间
     */
    public void setSection(String beginDate, String endDate, int[] colors) {

        this.beginDate = CalendarUtil.getDate(beginDate);
        this.endDate = CalendarUtil.getDate(endDate);
        if (this.beginDate == null) {
            this.beginDate = new GregorianCalendar(CalendarUtil.MIN_YEAR, 0, 1).getTime();
        }
        if (this.endDate == null) {
            this.endDate = new GregorianCalendar(CalendarUtil.MAX_YEAR, 11, 31).getTime();
        }
        // Log.i(TAG, "endDate is " + this.endDate);
        this.isSection = true;
        this.colors = colors;

    }

    /**
     * 判断日期是否在可选区域
     */
    private boolean dayisSection(Date date) {
        // Log.i(TAG, "begindate is :" + beginDate.toString());
        int i = date.compareTo(beginDate);
        int j = date.compareTo(endDate);
        if (i >= 0 && j <= 0) {
            return true;
        }
        return false;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        getDateBeans();
        
//        mMonthIndex = getArguments().getInt(INDEX);
//        
//        if (getArguments().getString(DATE_BEGIN) == null
//                && getArguments().getString(DATE_END) == null) {
//            return;
//        }
//
//        setSection(getArguments().getString(DATE_BEGIN), getArguments().getString(DATE_END),
//                getArguments().getIntArray(COLORS));
    }

    
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = null;
        view = inflater.inflate(R.layout.fragment_calendar, container, false);
        GridView grid = (GridView) view.findViewById(R.id.gridview);
        
        adapter = new CalendarGridAdapter(container.getContext());
        
        grid.setAdapter(adapter);
        grid.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View view, int position, long arg3) {

//                HashMap<String, Object> map = (HashMap<String, Object>) view.getTag();
//                // Log.i(TAG, map.toString());
//                if (Integer.parseInt(map.get("status").toString()) < 0) {
//                    return;
//                }
                
//                adapter.selectOption(position);
//                Date date = CalendarUtil.getDate(mMonthIndex);
//                SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-");
//                String d = df.format(date);
//                if(listener != null) {
//                    listener.setResult(d + map.get("day"));
//                }
                
                // Intent intent = new Intent();
                // intent.putExtra(CalendarActivity.RESULT_DATA, d + map.get("day"));
                // CalendarPagerFragment.this.getActivity().setResult(CalendarPagerFragment.this.getActivity().RESULT_OK,
                // intent);
                // CalendarPagerFragment.this.getActivity().finish();
            }

        });
        return view;

    }

    /**
     * 获取父activity,并且转换为CalendarResult
     */
    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
    }

    
    
    private List<HashMap<String, Object>> getDays() {
        int daynum = CalendarUtil.getDayNum(mMonthIndex);
        int dayweek = CalendarUtil.getDayWeek(mMonthIndex);
        int temp = 0;
        Date today =
                CalendarUtil.getDate(CalendarUtil.getCurrentMouth(), CalendarUtil.getCurrentDay());
        // 获得要显示的总数
        int total =
                ((dayweek + daynum - 1) * 1.0 / 7 - (dayweek + daynum - 1) / 7) > 0 ? ((dayweek
                        + daynum - 1) / 7 + 1) * 7 : dayweek + daynum - 1;
        // 获得要显示的两行时候首行的行数
        Calendar cal = Calendar.getInstance();
        int lineindex = 1;
        if (mMonthIndex == cal.get(Calendar.MONTH)
                + (cal.get(Calendar.YEAR) - CalendarUtil.MIN_YEAR) * 12) {
            cal.setTime(today);
            lineindex = (dayweek - 1 + cal.get(Calendar.DAY_OF_MONTH) - 1) / 7 + 1;
        }
        List<HashMap<String, Object>> days = new ArrayList<HashMap<String, Object>>();
        if (lineindex == 1) {
            for (int i = 1; i < dayweek; i++) {
                HashMap<String, Object> map = new HashMap<String, Object>();
                map.put("day", "");
                map.put("status", -1);
                days.add(map);
            }
            for (int i = 1; i <= (14 - (dayweek - 1)); i++) {
                HashMap<String, Object> map = new HashMap<String, Object>();
                map.put("day", i);
                if (this.isSection) { // 区间选择
                    map.put("status", -1);

                    Date newDay = CalendarUtil.getDate(this.mMonthIndex, i);
                    if (dayisSection(newDay)) {
                        map.put("status", 0);
                        map.put("color", colors[temp]);

                        temp++;
                        if (this.mMonthIndex == CalendarUtil.getCurrentMouth()
                                && dayisSection(today)) {
                            if (i == CalendarUtil.getCurrentDay()) {
                                map.put("status", 2);
                            }
                        } else {
                            if (this.mMonthIndex == CalendarUtil.getMouthsForDate(this.beginDate)) {
                                if (i == CalendarUtil.getDayForDate(this.beginDate)) {
                                    map.put("status", 1);
                                }
                            } else {
                                if (i == 1) {
                                    map.put("status", 1);
                                }
                            }
                        }
                    } else {
                        if (this.mMonthIndex == CalendarUtil.getCurrentMouth()
                                && i == CalendarUtil.getCurrentDay()) { // 判断是否是今天
                            map.put("status", -2);
                        }
                    }

                } else {
                    map.put("status", 0);
                    if (CalendarUtil.getCurrentDay() > daynum) { // 今天日期大于目前月份的天数
                        // 如果是第一天，设置为选中状态
                        if (i == 1) map.put("status", 1);

                    } else { // 今天的日期天不大于本月的天数

                        if (this.mMonthIndex == CalendarUtil.getCurrentMouth()
                                && i == CalendarUtil.getCurrentDay()) { // 如果年月日都和今天日期相同，设置为今天状态
                            map.put("status", 2);
                        } else if (i == CalendarUtil.getCurrentDay()) { // 只有日期和今天日期相同，设置为选中状态
                            map.put("status", 1);
                        }
                    }
                }
                // Log.i(TAG, map.toString());
                days.add(map);
            }
        } else {
            if (lineindex == (total - 1) / 7 + 1) lineindex--;
            int daymax =
                    (lineindex - 1) * 7 - (dayweek - 1) + 14 > daynum ? daynum : ((lineindex - 1)
                            * 7 - (dayweek - 1) + 14);
            for (int i = (lineindex - 1) * 7 - (dayweek - 1) + 1; i <= daymax; i++) {
                HashMap<String, Object> map = new HashMap<String, Object>();
                map.put("day", i);
                if (this.isSection) { // 区间选择
                    map.put("status", -1);

                    Date newDay = CalendarUtil.getDate(this.mMonthIndex, i);
                    if (dayisSection(newDay)) {
                        map.put("status", 0);
                        map.put("color", colors[temp]);

                        temp++;
                        if (this.mMonthIndex == CalendarUtil.getCurrentMouth()
                                && dayisSection(today)) {
                            if (i == CalendarUtil.getCurrentDay()) {
                                map.put("status", 2);
                            }
                        } else {
                            if (this.mMonthIndex == CalendarUtil.getMouthsForDate(this.beginDate)) {
                                if (i == CalendarUtil.getDayForDate(this.beginDate)) {
                                    map.put("status", 1);
                                }
                            } else {
                                if (i == 1) {
                                    map.put("status", 1);
                                }
                            }
                        }
                    } else {
                        if (this.mMonthIndex == CalendarUtil.getCurrentMouth()
                                && i == CalendarUtil.getCurrentDay()) { // 判断是否是今天
                            map.put("status", -2);
                        }
                    }

                } else {
                    map.put("status", 0);
                    if (CalendarUtil.getCurrentDay() > daynum) { // 今天日期大于目前月份的天数
                        // 如果是第一天，设置为选中状态
                        if (i == 1) map.put("status", 1);

                    } else { // 今天的日期天不大于本月的天数

                        if (this.mMonthIndex == CalendarUtil.getCurrentMouth()
                                && i == CalendarUtil.getCurrentDay()) { // 如果年月日都和今天日期相同，设置为今天状态
                            map.put("status", 2);
                        } else if (i == CalendarUtil.getCurrentDay()) { // 只有日期和今天日期相同，设置为选中状态
                            map.put("status", 1);
                        }
                    }
                }
                // Log.i(TAG, map.toString());
                days.add(map);
            }
        }
        return days;
    }

}
